package com.elysia.gulimall.ware.service.impl;

import com.elysia.common.constant.WareConstant;
import com.elysia.gulimall.ware.entity.PurchaseDetailEntity;
import com.elysia.gulimall.ware.service.PurchaseDetailService;
import com.elysia.gulimall.ware.service.WareInfoService;
import com.elysia.gulimall.ware.service.WareSkuService;
import com.elysia.gulimall.ware.vo.MergeVo;
import com.elysia.gulimall.ware.vo.PurchaseDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.elysia.common.utils.PageUtils;
import com.elysia.common.utils.Query;

import com.elysia.gulimall.ware.dao.PurchaseDao;
import com.elysia.gulimall.ware.entity.PurchaseEntity;
import com.elysia.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivedPurchase(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", WareConstant.PurchaseStatusEnum.CREATED.getCode())
                        .or().eq("status",WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId=mergeVo.getPurchaseId();
        if(purchaseId==null){
            //没有选择任何【采购单】，将自动创建新单进行合并
            PurchaseEntity purchaseEntity=new PurchaseEntity();
            //为采购单设置默认值，新建状态，创建更新的时间
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId=purchaseEntity.getId();
        }
        //确认采购单 状态  01 才能合并
        PurchaseEntity purchaseEntity=this.getById(purchaseId);
        if(purchaseEntity.getStatus()==WareConstant.PurchaseStatusEnum.CREATED.getCode()
                ||purchaseEntity.getStatus()==WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()){
            //合并采购需求，设置采购单id
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> collect = mergeVo.getItems().stream().map(detailId -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(detailId);
                detailEntity.setPurchaseId(finalPurchaseId);
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);

            //更新采购单的更新时间
            PurchaseEntity purchase=new PurchaseEntity();
            purchase.setId(purchaseId);
            purchase.setUpdateTime(new Date());
            this.updateById(purchase);
        }
    }

    /**
     * 领取采购单
     * @param purchaseIds 采购单id列表
     */
    @Transactional
    @Override
    public void receivePurchase(List<Long> purchaseIds) {
        //1.确认采购单状态
        List<PurchaseEntity> collect = this.listByIds(purchaseIds).stream().filter(purchaseEntity -> {
            return purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                    || purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode();
        }).map(purchaseEntity -> {
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            return purchaseEntity;
        }).collect(Collectors.toList());

        //2.修改采购单状态
        this.updateBatchById(collect);

        //3。修改采购项状态
        purchaseIds=collect.stream().map(item->{
            return item.getId();
        }).collect(Collectors.toList());
        List<PurchaseDetailEntity> detailEntities = purchaseDetailService.listDetailByPurchaseIds(purchaseIds).stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item.getId());
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.PURCHASING.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(detailEntities);
    }

    /**
     * 1.更新采购单状态
     * 2.更新采购项状态
     * 3.商品入库
     * @param doneVo
     */
    @Transactional
    @Override
    public void purchaseDone(PurchaseDoneVo doneVo) {
        final Boolean[] flag = {true};
        //更新采购项状态
        List<PurchaseDetailEntity> detailEntities = doneVo.getItems().stream().map(detail -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(detail.getItemId());
            purchaseDetailEntity.setStatus(detail.getStatus());
            if(detail.getStatus()==WareConstant.PurchaseDetailStatusEnum.EXIST_ERROR.getCode()){
                flag[0] =false;
            }else if(detail.getStatus()==WareConstant.PurchaseDetailStatusEnum.FINISH.getCode()){
                //入库
                PurchaseDetailEntity entity=purchaseDetailService.getById(detail.getItemId());
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
            }
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(detailEntities);

        //更新采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(doneVo.getId());
        purchaseEntity.setStatus(flag[0]?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.EXIST_ERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }
}